package com.longchat.service.impl.award;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.transaction.Transactional;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.longchat.domain.award.Activity;
import com.longchat.domain.award.Award;
import com.longchat.domain.award.AwardLog;
import com.longchat.dto.award.AwardLogInfo;
import com.longchat.dto.award.AwardResult;
import com.longchat.dto.comm.ResultEnum;
import com.longchat.dto.comm.ResultInfo;
import com.longchat.repository.ActivityJparepository;
import com.longchat.repository.AwardJpaRepository;
import com.longchat.repository.AwardLogJpaRepository;
import com.longchat.service.inter.award.IAwardService;
import com.longchat.utils.excel.LotteryUtil;
import com.longchat.utils.vo.ResultWrapper;

@Service

public class AwardService implements IAwardService {

	private static final Logger logger = LoggerFactory.getLogger(AwardService.class);
	@Autowired
	private AwardJpaRepository awardJpaRepository;
	
	@Autowired
	private AwardLogJpaRepository awardLogJpaRepository;
	@Autowired
	private ActivityJparepository activityJparepository;
	@Transactional
	@Override
	public ResultWrapper<AwardResult> award(Integer activityid,String openid,String nickName) {
		Activity activity = activityJparepository.findOne(activityid);
		if(activity==null){
			logger.error("奖品设置错误，必须包含一个没有奖品");
			return new ResultWrapper<AwardResult>().CustomStatus(505,"活动id参数错误");
		}else{
			Date nowDate = Calendar.getInstance().getTime();
			if(activity.getStartTime().after(nowDate)){
				logger.info("活动还没开始");
				return new ResultWrapper<AwardResult>().CustomStatus(501,"抽奖活动还没有开始");
			}else if(activity.getEndTime().before(nowDate)){
				logger.info("活动已经结束");
				return new ResultWrapper<AwardResult>().CustomStatus(501,"抽奖活动已经结束");
			}else{
				List<AwardLog> queryAwards = awardLogJpaRepository.findByOpenid(openid);
				if(queryAwards!=null&&queryAwards.size()>=activity.getActCount()){
					logger.info("该抽奖您已经没有机会，您已经抽奖");
					return new ResultWrapper().CustomStatus(502,"该抽奖您已经没有机会，您已经抽奖"+activity.getActCount()+"次");
				}
			}
		}
		List<Award> prizeArr = awardJpaRepository.findAll();
		Object[] result = award(prizeArr);
		AwardLog log = new AwardLog();
		Award award = null;
		if(result!=null){
			award = awardJpaRepository.findOne((int)result[1]);
		}
		if(award!=null&&(award.getRemain()==null||award.getRemain()>0)){
			log.setAward(award);
			log.setNickName(nickName);
			log.setOpenid(openid);
			log.setTime(Calendar.getInstance().getTime());
			awardLogJpaRepository.save(log);
		}else{
			List<Award> notHasPrizeAwards = awardJpaRepository.findNotHasPrize();
			if(notHasPrizeAwards==null||notHasPrizeAwards.size()==0){
				logger.error("奖品设置错误，必须包含一个没有奖品");
				throw new RuntimeException("奖品设置错误，必须包含一个没有奖品");
			}
			Award notHasPrizeAward = notHasPrizeAwards.get(0);
			int angle = new Random().nextInt(notHasPrizeAward.getMaxAngle()-notHasPrizeAward.getMinAngle())+notHasPrizeAward.getMinAngle();
			String msg = notHasPrizeAward.getName();//提示信息
	        result = new Object[]{angle,notHasPrizeAward.getId(),msg};
	        log.setAward(notHasPrizeAward);
			log.setOpenid(openid);
			log.setNickName(nickName);
			log.setTime(Calendar.getInstance().getTime());
			awardLogJpaRepository.save(log);
		}
		AwardResult awardResult = new AwardResult();
		awardResult.setAngle((int)result[0]);
		awardResult.setMsg((String)result[2]);
		
		return new ResultWrapper<AwardResult>().OKWithData(awardResult);
	}

	//抽奖并返回角度和奖项
    public Object[] award(List<Award> prizeArr){
        //获得概率数组
        List<Double> orignalRates = new ArrayList<Double>(prizeArr.size());
        for (int i =0; i<prizeArr.size(); i++){
            orignalRates.add(prizeArr.get(i).getRate());
        }

        //获得奖项id
        int prizeIndex = LotteryUtil.lottery(orignalRates);
        if(prizeIndex==-1){
        	return null;
        }
        logger.debug("prizeIndex:{},prizeArr={}",prizeIndex,prizeArr);
        Award award = prizeArr.get(prizeIndex);
        int prizeId = award.getId(); //根据概率获取奖项id
        //旋转角度
        int angle = new Random().nextInt(award.getMaxAngle()-award.getMinAngle())+award.getMinAngle();
        String msg = award.getName();//提示信息
        return new Object[]{angle,prizeId,msg};
    }

	@Override
	public ResultWrapper<List<Award>> findAllAward(Integer activityId) {
		return new ResultWrapper<List<Award>>().OKWithData(awardJpaRepository.findAwardByActivityId(activityId));
	}

	@Override
	public ResultWrapper<List<AwardLogInfo>> findAwardLog(String openid) {
		List<AwardLog> awardlogs = awardLogJpaRepository.findByOpenid(openid);
		List<AwardLogInfo> infos = new ArrayList<>();
		for(AwardLog a:awardlogs){
			AwardLogInfo info = new AwardLogInfo();
			info.setAwardName(a.getAward().getName());
			info.setTime(DateFormatUtils.format(a.getTime(),"yyyy-MM-dd HH:mm:ss"));
			infos.add(info);
		}
		return new ResultWrapper<List<AwardLogInfo>>().OKWithData(infos);
	}

	@Override
	public ResultWrapper<String> updateAward(Award award) {
		awardJpaRepository.save(award);
		return new ResultWrapper<String>().OK();
	}

	@Override
	public ResultWrapper<String> addAward(Award award) {
		awardJpaRepository.save(award);
		return new ResultWrapper<String>().OK();
	}

	@Override
	public ResultWrapper<String> deleteAward(int id) {
		
		 awardJpaRepository.delete(id);
		 return new ResultWrapper<String>().OK();
	}

	@Override
	public Award findAwardById(int id) {
		return awardJpaRepository.findOne(id);
	}

	@Override
	public List<AwardLog> findAllAwardLogs() {
		return awardLogJpaRepository.findAll();
	}

	@Override
	public Activity findActivity(Integer activityId) {
		
		return activityJparepository.findOne(activityId);
	}

	@Override
	public List<Activity> findAllActivity() {
		return activityJparepository.findAll();
	}

	@Override
	public ResultInfo updateActivity(Activity activity) {
		activityJparepository.save(activity);
		return new ResultInfo<>(ResultEnum.SUCCESS);
	}
	
	


}
